/*
 * 公共函数
 *
 * */

import _ from 'lodash';
import { FormInstanceFunctions } from 'tdesign-vue-next';
import { reactive, ref } from 'vue';

import { PAGE_DATA } from '@/constants';
import { IObject } from '@/types/common';

interface IOptions {
  initData: IObject;
}

export const useListPage = (getData: () => void, options?: IOptions) => {
  const { initData } = options || {};

  const pageData = reactive(_.cloneDeep(PAGE_DATA));
  const formRef = ref<FormInstanceFunctions>();
  const formData = ref({ ...initData });

  const search = () => {
    pageData.params.page = 1;
    getData();
  };

  const reset = () => {
    formRef.value.reset();
    formData.value = { ...initData };
    search();
  };

  const getIndex = (num: number) => {
    const { page, size } = pageData.params || {};
    return (page - 1) * size + num + 1;
  };

  const handlePageChange = (data: any) => {
    const { current, pageSize } = data;
    pageData.params.page = current;
    pageData.params.size = pageSize;
    getData();
  };

  return { getIndex, formData, pageData, formRef, search, reset, handlePageChange };
};
